package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.BdMerchant;
import com.example.demo.mapper.MerchantMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/merchant")
public class MerchantController extends BaseController{

    @Resource
    MerchantMapper merchantMapper;

    @PostMapping
    public Result<?> save(@RequestBody BdMerchant bdMerchant) {
        bdMerchant.setCreateTime(new Date());
        merchantMapper.insert(bdMerchant);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody BdMerchant bdMerchant) {
        bdMerchant.setUpdateTime(new Date());
        merchantMapper.updateById(bdMerchant);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        merchantMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Integer id) {
        return Result.success(merchantMapper.selectById(id));
    }

//    /**
//     * 注意：这个方法使用的是Mybatis sql的方式做的多表联合查询，大家可以点开，参考下怎么写多表查询
//     * @param userId
//     * @return
//     */
//    @GetMapping("/{userId}")
//    public Result<?> getByUserId(@PathVariable Integer userId) {
//        return Result.success(merchantMapper.findByUserId(userId));
//    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String contractNumber,
                              @RequestParam(defaultValue = "") String name) {
        LambdaQueryWrapper<BdMerchant> wrapper = Wrappers.<BdMerchant>lambdaQuery();
        if (StrUtil.isNotBlank(name)) {
            wrapper.like(BdMerchant::getName, name);
        }
        if (StrUtil.isNotBlank(contractNumber)) {
            wrapper.like(BdMerchant::getContractNumber, contractNumber);
        }
        Page<BdMerchant> merchantPage = merchantMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(merchantPage);
    }
}
